package com.qi.services.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qi.exception.ServerException;
import com.qi.mapper.MessageMapper;
import com.qi.pojo.entity.Message;
import com.qi.pojo.entity.User;
import com.qi.services.IMessageService;
import com.qi.services.IUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Resource
    private IUserService userService;

    @Override
    public void postMsg(String content) {
        if (StrUtil.isBlank(content)) {
            throw new ServerException("参数异常");
        }
        Message message = new Message();
        User curUser = userService.getCurUserInfo();
        message.setPostUserId(curUser.getId());
        message.setContent(content);
        message.setClubId(curUser.getClubId());
        this.save(message);
    }

    @Override
    public IPage<Message> getMsgList(Long current, Long size) {
        User curUser = userService.getCurUserInfo();
        IPage<Message> msgPage = new Page<>(current, size);
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<Message>()
                .eq(Message::getClubId, curUser.getClubId())
                .orderByDesc(Message::getPostTime);
        msgPage = this.page(msgPage, queryWrapper);
        for (Message record : msgPage.getRecords()) {
            Long postUserId = record.getPostUserId();
            User postUser = userService.getById(postUserId);
            record.setPostName(postUser.getName());
        }
        return msgPage;
    }
}
